package com.lmf.mock.starter.autoconfigure.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lmf.mock.starter.autoconfigure.entity.MockApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 真实数据拉取服务
 */
@Service
public class RealDataService {

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private MockApiService mockApiService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 从真实URL拉取数据
     * 
     * @param apiId API ID
     * @return 响应数据
     */
    public String fetchRealData(Long apiId) throws Exception {
        MockApi api = mockApiService.getById(apiId);
        if (api == null) {
            throw new RuntimeException("接口不存在");
        }
        
        String realUrl = api.getRealUrl();
        if (realUrl == null || realUrl.trim().isEmpty()) {
            throw new RuntimeException("未配置真实URL");
        }
        
        // 从数据库中获取请求参数
        Map<String, Object> params = new HashMap<>();
        if (api.getRequestParams() != null && !api.getRequestParams().trim().isEmpty()) {
            try {
                params = objectMapper.readValue(api.getRequestParams(), Map.class);
            } catch (Exception e) {
                throw new RuntimeException("请求参数JSON格式错误: " + e.getMessage());
            }
        }
        
        // 构建请求URL
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(realUrl);
        
        // 添加查询参数（对于GET请求）
        if ("GET".equalsIgnoreCase(api.getHttpMethod()) && !params.isEmpty()) {
            params.forEach((key, value) -> uriBuilder.queryParam(key, value));
        }
        
        URI uri = uriBuilder.build().toUri();
        
        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        
        HttpEntity<?> requestEntity;
        
        // 根据HTTP方法构建请求实体
        switch (api.getHttpMethod().toUpperCase()) {
            case "GET":
            case "DELETE":
                requestEntity = new HttpEntity<>(httpHeaders);
                break;
            case "POST":
            case "PUT":
            case "PATCH":
                // 对于POST等请求，将参数作为请求体
                if (!params.isEmpty()) {
                    requestEntity = new HttpEntity<>(params, httpHeaders);
                } else {
                    requestEntity = new HttpEntity<>(httpHeaders);
                }
                break;
            default:
                requestEntity = new HttpEntity<>(httpHeaders);
        }
        
        // 发送请求
        HttpMethod httpMethod = HttpMethod.valueOf(api.getHttpMethod().toUpperCase());
        ResponseEntity<String> response = restTemplate.exchange(uri, httpMethod, requestEntity, String.class);
        
        return response.getBody();
    }
    
    /**
     * 按分组批量拉取真实数据
     * 
     * @param groupId 分组ID
     * @return 批量拉取结果
     */
    public Map<String, Object> fetchRealDataByGroup(Long groupId) {
        Map<String, Object> result = new HashMap<>();
        Map<String, String> details = new HashMap<>();
        
        List<MockApi> apis = mockApiService.getApisByGroupId(groupId);
        
        // 过滤出配置了真实URL的接口
        List<MockApi> realUrlApis = apis.stream()
            .filter(api -> api.getRealUrl() != null && !api.getRealUrl().trim().isEmpty())
            .collect(Collectors.toList());
        
        if (realUrlApis.isEmpty()) {
            result.put("success", false);
            result.put("message", "该分组下没有配置真实URL的接口");
            result.put("successCount", 0);
            result.put("failCount", 0);
            result.put("details", details);
            return result;
        }
        
        int successCount = 0;
        int failCount = 0;
        
        for (MockApi api : realUrlApis) {
            try {
                String realData = fetchRealData(api.getId());
                
                // 更新接口的响应数据
                api.setResponseData(realData);
                mockApiService.updateApi(api);
                
                details.put(api.getApiName(), "成功");
                successCount++;
            } catch (Exception e) {
                details.put(api.getApiName(), "失败: " + e.getMessage());
                failCount++;
            }
        }
        
        result.put("success", successCount > 0);
        result.put("message", String.format("批量拉取完成，成功: %d，失败: %d", successCount, failCount));
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("details", details);
        
        return result;
    }
    
    /**
     * 验证URL是否可访问
     * 
     * @param url URL地址
     * @return 是否可访问
     */
    public boolean validateUrl(String url) {
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.HEAD, new HttpEntity<>(new HttpHeaders()), String.class);
            return response.getStatusCode().is2xxSuccessful();
        } catch (Exception e) {
            return false;
        }
    }
}